# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2023/1/17 10:01
@describe: 启动文件
"""
import sys
import os
import subprocess

from util.run_case import RunCase
from util.html_result.html_result import generate_html
from pathlib import Path


# noinspection PyBroadException
def main():
	# sg.theme("DarkAmber")
	report = None
	env_list = ["saas_test", "saas_qa"]
	layout = [
		[sg.FileBrowse('选择文件', key="file", enable_events=True), sg.Text()],
		[
			sg.Text("选择环境："), sg.Combo(env_list, default_value=env_list[0], key="combo"),
			sg.Button("开始测试", key="start"),
			sg.Button("打开测试报告", key="open_report")
		],
		[sg.Output(size=(60, 20))],
	]

	# Create the Window
	window = sg.Window(
		'模糊测试工具',
		layout,
		default_element_size=(30, 2)
	)
	# init window
	WindowPrint(window)
	# Event Loop to process "events"
	while True:
		event, values = window.read()
		if event in (sg.WIN_CLOSED,):
			break
		if event == "start":
			if values.get("file", ""):
				try:
					r = RunCase()
					r(**{"file": values['file'], "env": values["combo"], "window": window})
					generate_html(obj=r, window=window)
					WindowPrint().print("测试报告生成完成!")
					report = "ok"
				except Exception as e:
					WindowPrint().print(e)
			else:
				WindowPrint().print("请先上传文件!")
		if event == "open_report":
			if report == "ok":
				try:
					if sys.platform == "darwin":
						subprocess.call(
							["open", Path(__file__).parent / "util" / "html_result" / "output" / "index.html"])
					else:
						os.startfile(Path(__file__).parent / "util" / "html_result" / "output" / "index.html")
				except Exception as e:
					WindowPrint().print(e)
			else:
				WindowPrint().print("无测试报告!")

	window.close()


if __name__ == '__main__':
	a = os.popen("pip3 install -r requirements.txt").read()
	print(a)

	import PySimpleGUI as sg
	from util.common import WindowPrint

	main()
